package com.example.spgl.controller;

import com.example.spgl.service.UserService;
import com.example.spgl.entity.Result;
import com.example.spgl.entity.User;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    //注册功能
    @PostMapping("/register")
    public Result register(String username, String password, String name) {
        User u = userService.findByUsername(username);//查询是否有相同名称的用户
        if(u==null){
            userService.register(username,password,name);
            return Result.success();
        }else{
            return Result.error("用户名已被占用");
        }
    }

    @PostMapping("/login")
    //用户登录
    public Result<User> Login(HttpServletRequest request,String username, String password){
        User u = userService.findByUsername(username);
        if(u==null){
            return Result.error("用户不存在");
        }else if(u.getPassword().equals(password)){
            request.getSession().setAttribute("userInfo",username);
            return Result.success(u);
        }
        return Result.error("用户名或密码错误");
    }

    @GetMapping("/mylist")
    public Result<User> mylist(String username){
        User u = userService.findByUsername(username);
        return Result.success(u);
    }

    @PostMapping("/logout")
    public Result<String> logout(HttpServletRequest request){
        request.getSession().removeAttribute("userInfo");
        return Result.success("退出成功");
    }
}
